package com.hula.onion.book.server.spider.platforms.itouzi;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Created by work on 2018/1/21.
 */
@Component("iTouZiSpider")
public class ITouZiSpider extends SpiderCommon {

    @Autowired
    private ITouZiSpiderHelper touZiSpiderHelper;

    private static final String LOGIN_HTML_URL = "https://www.itouzi.com/login";

    private static final String LOGIN_URL = "https://www.itouzi.com/user/ajax/login";

    private static final String USER_INFO_URL = "https://www.itouzi.com/user";

    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);

        HttpClientContext httpContext = new HttpClientContext();
        BasicCookieStore cookieStore = new BasicCookieStore();
        httpContext.setCookieStore(cookieStore);

        //先请求一次首页获取cookies
        HttpUtils.get(LOGIN_HTML_URL, httpContext);

        Map<String, Object> params = touZiSpiderHelper.installRequestParams(loginForm);

        //模拟登陆
        String str = HttpUtils.post(LOGIN_URL, params, httpContext);

        if (!StringUtils.isEmpty(str)) {

            int code = JSONObject.parseObject(str).getInteger("code");
            //登陆成功
            if (code == 0) {

                String html = HttpUtils.get(USER_INFO_URL, httpContext);

                AccountInfo accountInfo = touZiSpiderHelper.parseAccountInfo(html);

                commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);

                commonResponse.setData(accountInfo);
                return commonResponse;

            } else {
                commonResponse = new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
                commonResponse.setMsg(JSONObject.parseObject(str).getString("info"));

                return commonResponse;
            }
        }

        return commonResponse;
    }
}
